﻿using Halcon二次开发.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HalconDotNet;
using Halcon二次开发.Data.SocketChild数据;
using Halcon二次开发.Controller.通信;
using Halcon二次开发.Model.储放所有单例.储存每个单例界面;
using System.Threading;
using Halcon二次开发.Model.自定义控件;

namespace Halcon二次开发.View.Socket通信
{
    public partial class SocketChildForm : Form
    {
        /// <summary>
        /// 文本数据
        /// </summary>
        public BindingList<SocketDome> blist=new BindingList<SocketDome>();
        public void i()
        {
            uiDataGridView1.DataSource = blist;

        }
        /// <summary>
        /// 动作对象
        /// </summary>
        public SocketControllerChild controller;
        /// <summary>
        /// 输入计数器
        /// </summary>
        public int count;
        /// <summary>
        /// 编辑值前发生
        /// </summary>
        string beginValue;
        /// <summary>
        /// 编辑值后发生
        /// </summary>
        string endValue;

        /// <summary>
        /// 编辑值前集合
        /// </summary>
        List<string> beginList = new List<string>();

        /// <summary>
        /// 名称改变时通知节点改变
        /// </summary>
       public Action<SocketDome> nameChanged;
        /// <summary>
        /// 当前鼠标点击的子节点对象
        /// </summary>
        TreeNode mouseNode;

        HwindowFlowNodeUrseControl hwindowFlowNode;
        public SocketChildForm(HwindowFlowNodeUrseControl hwindowFlowNode)
        {
            InitializeComponent();
            this.hwindowFlowNode = hwindowFlowNode;
            controller = new SocketControllerChild(this, $"Data\\工程文件\\{hwindowFlowNode.name}工程文件\\Socket工具数据",hwindowFlowNode);
            uiDataGridView1.DataSource = blist;
            uiDataGridView1.Columns[2].DefaultCellStyle.BackColor= Color.Green;
         nameChanged = NameChanged;
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        /// <summary>
        /// 名称改变时通知节点改变
        /// </summary>
        /// <param name="obj"></param>
        private void NameChanged(SocketDome socketDome)
        {
            foreach (TreeNode item in treeView1.Nodes[0].Nodes)
            {
                if ((item.Tag as SocketDome) == socketDome)
                {
                    if (item.Text.Contains("<—"))
                    {
                       string[] str= item.Text.Split(new char[] { '<', '—' }, StringSplitOptions.RemoveEmptyEntries);
                        item.Text = item.Text.Replace(str[0], socketDome.Name);
                    }else
                    {
                        item.Text = socketDome.Name;
                    }
                    item.Name = socketDome.Name;
                }
            }
        }
        /// <summary>
        /// 添加按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            SocketDome newDome= controller.Add(blist,ref count,nameChanged);
            AddNode(newDome,newDome.Name,newDome.Name);
        }
        /// <summary>
        /// 添加节点方法
        /// </summary>
        /// <param name="newDome"></param>
        public void AddNode(SocketDome newDome,string name,string text)
        {
            //往节点添加
            TreeNode treeNode = new TreeNode();
            treeView1.Nodes[0].Nodes.Add(treeNode);
            //绑定SocketDome
            treeNode.Tag = newDome;
            treeNode.Name = name;
            treeNode.Text = text;
            if (name != text)
            {
                treeNode.ForeColor = Color.Green;
            }
            ContextMenuStrip contex = new ContextMenuStrip();// 右击菜单

            ToolStripMenuItem toolStrip1 = new ToolStripMenuItem("连接至");//子菜单1
            toolStrip1.Tag = treeNode;

            ToolStripMenuItem toolStrip2 = new ToolStripMenuItem("取消连接");//子菜单2
            toolStrip2.Click += ToolStrip2_Click;
            toolStrip2.Tag = treeNode;

            contex.Items.Add(toolStrip1);
            contex.Items.Add(toolStrip2);

            treeNode.ContextMenuStrip = contex;
        }
        /// <summary>
        /// 生成可以连接的元素
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                mouseNode = treeView1.GetNodeAt(e.X, e.Y);
                if (mouseNode != null && mouseNode.Parent==treeView1.Nodes[0])
                { 
                    //工程文件的大treeview
                    TreeView treeView = hwindowFlowNode.treeView1;
                    int index = treeView.Nodes.IndexOf(this.Tag as TreeNode);
                    if (index == 0) return;
                    //获取右击菜单
                    ContextMenuStrip context = mouseNode.ContextMenuStrip;
                    (context.Items[0] as ToolStripMenuItem).DropDownItems.Clear();
                    for (int i = 0; i < treeView.Nodes.Count; i++)
                    {
                        foreach (TreeNode childNode in treeView.Nodes[i].Nodes)//子节点
                        {
                            //通过反射 获取当前遍历的节点（字段）
                            FieldInfo itemInfo = childNode.Tag.GetType().GetField(childNode.Name);
                            if (childNode.Text.Contains("Out") && "HObject" != itemInfo.FieldType.Name)
                            {
                                ToolStripMenuItem menuItem1 = new ToolStripMenuItem(treeView.Nodes[i].Name + "." + childNode.Name);
                                menuItem1.Tag = childNode.Tag;
                                  menuItem1.Click += MenuItem1_Click; ;
                                (context.Items[0] as ToolStripMenuItem).DropDownItems.Add(menuItem1);
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 取消连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ToolStrip2_Click(object sender, EventArgs e)
        {
            object obj = (sender as ToolStripMenuItem).Tag;
            if (obj != null)
            {
                TreeNode node = (sender as ToolStripMenuItem).Tag as TreeNode;
                if (node.Text.Contains("<—"))
                {
                    node.Text = node.Name;
                    node.ForeColor = Color.Black;
                }
               
            }

        }
        /// <summary>
        /// 连接节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MenuItem1_Click(object sender, EventArgs e)
        {
            if (mouseNode != null && mouseNode.ForeColor != Color.Green)
            {
                //先记录进来之间的节点名字
                mouseNode.Text = mouseNode.Name + "<—" + (sender as ToolStripMenuItem).Text;
                mouseNode.ForeColor = Color.Green;

                string[] str = mouseNode.Text.Split(new char[] { '<', '—', '.' }, StringSplitOptions.RemoveEmptyEntries);
                string formName= str[1].Trim();

                string filderName = str[2].Trim();
                //工程文件的大treeview
                TreeView treeView = hwindowFlowNode.treeView1;

                //连接完成，获得值
                foreach (TreeNode node in treeView.Nodes)
                {
                    if (node.Text == formName)
                    {
                        object o = node.Nodes[0].Tag;
                        FieldInfo fieldInfo = o.GetType().GetField(filderName);
                        object v = fieldInfo.GetValue(o);
                        (mouseNode.Tag as SocketDome).Result = v.ToString();
                        uiDataGridView1.Refresh();
                    }
                }
            }
        }

        /// <summary>
        /// 删除按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            if (uiDataGridView1.SelectedIndex == -1 || uiDataGridView1.RowCount==0 ) return;
            treeView1.Nodes[0].Nodes.RemoveAt(uiDataGridView1.SelectedIndex);
            controller.Delete(blist, uiDataGridView1.SelectedIndex);
        }
        /// <summary>
        /// 上移按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            int index= uiDataGridView1.SelectedIndex;
            controller.MoveUp(blist,index);
        }
        /// <summary>
        /// 下移按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            int index = uiDataGridView1.SelectedIndex;
            controller.DownMove(blist, index);
        }
        /// <summary>
        /// 运行按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            try
            {
                controller.Run();
            }
            catch(Exception ex)
            {
                (FormDb.Db["Form1"] as Form1).textBox1.AppendText(this.Name + ":" + ex.Message + "\r\n");
            }
        }
        /// <summary>
        /// 单元格值发生改变后
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiDataGridView1_CellEndEdit_1(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == -1 || e.RowIndex == -1 || e.ColumnIndex!=0 || e.RowIndex>uiDataGridView1.RowCount - 1) return;
            endValue= uiDataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
            if (endValue == beginValue) return;
            if (endValue.Trim() == "")
            {
                MessageBox.Show("名称不能为空", "重命名错误");
            }
            string ss = beginList.Find(s => s.Trim() == endValue.Trim());
            if (ss != null )
            {
                uiDataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = beginValue;
                MessageBox.Show("集合具有相同的名称", "重命名错误");
            }
        }
        /// <summary>
        /// 单元格值发生改变前
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiDataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (e.ColumnIndex == -1 || e.RowIndex == -1 || e.ColumnIndex != 0 || e.RowIndex > uiDataGridView1.RowCount - 1) return;
            beginValue = uiDataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
            beginList.Clear();
            foreach (var item in blist)
            {
                beginList.Add(item.Name);
            }

        }
        /// <summary>
        /// 窗体结束事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SocketChildForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.Hide();
            e.Cancel = true;

            controller.SetLists();
            controller.SetNodes();
        }

        /// <summary>
        /// 反射调用该方法更新窗体句柄
        /// </summary>
        /// <param name="hwindowFlowNode"></param>
        public void PushHWindon(HwindowFlowNodeUrseControl hwindowFlowNode) { 
            this.hwindowFlowNode = hwindowFlowNode;
            controller.hwindowFlowNode = hwindowFlowNode;
        }
    }
}
